﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;

namespace FSUtility
{
    /// <summary>
    /// 图片对比处理
    /// </summary>
    public class ImageCompareHandler
    {
        /// <summary>
        /// 比较两幅图片是否一致
        /// </summary>
        /// <param name="imgLeft">左侧图片</param>
        /// <param name="imgRight">右侧图片</param>
        /// <param name="compareSize">要比较的单元大小,默认大小为（20,20）</param>
        /// <returns>不一致的地方</returns>
        public List<Rectangle> CompareImage(Bitmap imgLeft, Bitmap imgRight, Size compareSize)
        {
            if (imgLeft.Size != imgRight.Size)
            {
                throw new Exception("图片大小不一致");
            }

            if (compareSize == Size.Empty)
            {
                compareSize = new Size(20, 20);
            }

            List<Rectangle> allDiffentRect = new List<Rectangle>();
            //比较图像
            //以compareSize大小将图像划分为网格
            int compareRow = imgLeft.Height / compareSize.Height; //在行上的比较次数，去掉外围内容
            int compareColumn = imgLeft.Width / compareSize.Width;

            int gridTop = 0, gridLeft = 0;

            //循环遍历每一个网格，提却其像素大小，如果不同，就记录该网格
            for (int row = 0; row < compareRow; row++)
            {
                for (int col = 0; col < compareColumn; col++)
                {
                    gridTop = row * compareSize.Height;
                    gridLeft = col * compareSize.Width;
                    //循环遍历小方格,一列一列的比较，也可以逐行比较
                    for (int gridX = 0; gridX < compareSize.Width; gridX++)
                    {
                        for (int gridY = 0; gridY < compareSize.Height; gridY++)
                        {
                            if (imgLeft.GetPixel(gridLeft + gridX, gridTop + gridY)
                                != imgRight.GetPixel(gridLeft + gridX, gridTop + gridY))
                            {
                                allDiffentRect.Add(new Rectangle(new Point(gridLeft, gridTop), compareSize));
                                goto ReturnGrid;
                            }
                        }
                    }

                ReturnGrid: ;
                }
            }
            //返回结果
            return allDiffentRect;
        }
    }
}
